package gui;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.*;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JTextField;

import control.*;
import model.*;

import javax.swing.JButton;
import javax.swing.JSeparator;

public class SaleMenu extends JFrame {

	private JPanel contentPane;
	private JTextField idField;
	private JTextField dateField;
	private JTextField statusField;
	private JTextField deliveryDateField;
	private JTextField pIdField;
	private JTextField amountField;
	private JTextField priceField;
	private JTextField totalPriceField;
	private SalesOrderCtrl salesCtrl = new SalesOrderCtrl();
	private CustomerCtrl custCtrl = new CustomerCtrl();
	private LineItemCtrl lineItemCtrl = new LineItemCtrl();
	private ProductCtrl productCtrl = new ProductCtrl();
	private CustomerGroupCtrl custGrpCtrl = new CustomerGroupCtrl();
	private JTextField customerField;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					SaleMenu frame = new SaleMenu();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public SaleMenu() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 640, 350);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JLabel lblSaleDetails = new JLabel("Sale details");
		lblSaleDetails.setFont(new Font("Tahoma", Font.PLAIN, 15));
		lblSaleDetails.setBounds(25, 11, 87, 14);
		contentPane.add(lblSaleDetails);
		
		JLabel lblId = new JLabel("ID");
		lblId.setBounds(25, 36, 46, 14);
		contentPane.add(lblId);
		
		JLabel lblDate = new JLabel("Date");
		lblDate.setBounds(25, 61, 46, 14);
		contentPane.add(lblDate);
		
		JLabel lblDeliveryDate = new JLabel("Delivery date");
		lblDeliveryDate.setBounds(25, 111, 74, 14);
		contentPane.add(lblDeliveryDate);
		
		JLabel lblDeliveryStatus = new JLabel("Delivery status");
		lblDeliveryStatus.setBounds(25, 86, 74, 14);
		contentPane.add(lblDeliveryStatus);
		
		JLabel lblNewLabel_1 = new JLabel("Item details");
		lblNewLabel_1.setFont(new Font("Tahoma", Font.PLAIN, 13));
		lblNewLabel_1.setBounds(25, 171, 87, 14);
		contentPane.add(lblNewLabel_1);
		
		JLabel lblProductId = new JLabel("Product id");
		lblProductId.setBounds(25, 196, 63, 14);
		contentPane.add(lblProductId);
		
		JLabel lblAmount = new JLabel("Amount");
		lblAmount.setBounds(25, 221, 46, 14);
		contentPane.add(lblAmount);
		
		JLabel lblItemPrice = new JLabel("Item price");
		lblItemPrice.setBounds(25, 246, 74, 14);
		contentPane.add(lblItemPrice);
		
		idField = new JTextField();
		idField.setBounds(134, 33, 86, 20);
		contentPane.add(idField);
		idField.setColumns(10);
		
		dateField = new JTextField();
		dateField.setBounds(134, 58, 86, 20);
		contentPane.add(dateField);
		dateField.setColumns(10);
		
		statusField = new JTextField();
		statusField.setBounds(134, 83, 86, 20);
		contentPane.add(statusField);
		statusField.setColumns(10);
		
		deliveryDateField = new JTextField();
		deliveryDateField.setBounds(134, 108, 86, 20);
		contentPane.add(deliveryDateField);
		deliveryDateField.setColumns(10);
		
		pIdField = new JTextField();
		pIdField.setBounds(134, 193, 86, 20);
		contentPane.add(pIdField);
		pIdField.setColumns(10);
		
		amountField = new JTextField();
		amountField.setBounds(134, 218, 86, 20);
		contentPane.add(amountField);
		amountField.setColumns(10);
		
		priceField = new JTextField();
		priceField.setBounds(134, 243, 86, 20);
		contentPane.add(priceField);
		priceField.setColumns(10);
		
		JLabel lblTotalPrice = new JLabel("Total price");
		lblTotalPrice.setBounds(25, 280, 63, 14);
		contentPane.add(lblTotalPrice);
		
		totalPriceField = new JTextField();
		totalPriceField.setEditable(false);
		totalPriceField.setBounds(134, 277, 86, 20);
		contentPane.add(totalPriceField);
		totalPriceField.setColumns(10);
		
		JButton btnAddSale = new JButton("Add sale");
		btnAddSale.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				/*if(idField.getText().equals("") || dateField.getText().equals("") || deliveryDateField.getText().equals("") || statusField.getText().equals("") || customerField.getText().equals(""))
				{
					JOptionPane.showMessageDialog(null,"One of the fields is empty.");
				}
				else 
					if(!isNumeric(idField.getText()))
					{
						JOptionPane.showMessageDialog(null,"The field ID must contain a number.");
					}
					else
						if(salesCtrl.getSalesOrderId(idField.getText()) != null)
						{
							JOptionPane.showMessageDialog(null,"A sale with this ID already exists!");
						}
						else
							if(custCtrl.getCustomerID(customerField.getText()) == null)
							{
								JOptionPane.showMessageDialog(null,"This customer ID is invalid!");
							}
						else
						{*/
							try {
								salesCtrl.insertSalesOrder(Integer.parseInt(idField.getText()), dateField.getText(), statusField.getText(), deliveryDateField.getText(), 0, Integer.parseInt(customerField.getText()));
							} catch (Exception e1) {
								JOptionPane.showMessageDialog(null,"Error in creating Sale!");
							} 
			}
		});
		btnAddSale.setBounds(362, 32, 105, 23);
		contentPane.add(btnAddSale);
		
		JButton btnDeleteSale = new JButton("Delete sale");
		btnDeleteSale.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(idField.getText().equals(""))
				{
					JOptionPane.showMessageDialog(null, "The ID field must not be empty.");
				}
				else
					if(!isNumeric(idField.getText()))
					{
						JOptionPane.showMessageDialog(null, "The ID field must contain only digits.");
					}
					else
						if(salesCtrl.getSalesOrderId(idField.getText()) == null)
						{
							JOptionPane.showMessageDialog(null, "The id specified must exist in the database.");
						}
						else
						{
							salesCtrl.deleteSalesOrder(idField.getText());
							ArrayList <LineItem> lineItems = lineItemCtrl.getAllLineItems();
							for(LineItem lineItem : lineItems)
							{
								if(String.valueOf(lineItem.getSaleId()).equals(idField.getText()))
								{
									lineItemCtrl.deleteLineItem(idField.getText());
								}
							}
						}
			}	
			});
		btnDeleteSale.setBounds(362, 82, 105, 23);
		contentPane.add(btnDeleteSale);
		
		JButton btnUpdateSale = new JButton("Update sale");
		btnUpdateSale.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(idField.getText().equals(""))
				{
					JOptionPane.showMessageDialog(null, "Please specify the id of the sale you want to change.");
				}
				else
					if(!isNumeric(idField.getText()))
					{
						JOptionPane.showMessageDialog(null, "The ID field must contain only digits.");
					}
					else
						if(salesCtrl.getSalesOrderId(idField.getText()) == null)
						{
							JOptionPane.showMessageDialog(null, "The ID must exist in the database.");
						}
						else
						{
							SalesOrder toUpdate = new SalesOrder();
							toUpdate = salesCtrl.getSalesOrderId(idField.getText());
							if(!dateField.getText().equals("")) toUpdate.setDate(dateField.getText());
							if(!statusField.getText().equals("")) toUpdate.setDeliveryStatus(statusField.getText());
							if(!deliveryDateField.getText().equals("")) toUpdate.setDeliveryDate(deliveryDateField.getText());
							if(!customerField.getText().equals("")) toUpdate.setCustomerId(Integer.parseInt(customerField.getText()));
							salesCtrl.updateSalesOrder(toUpdate.getId(), toUpdate.getDate(), toUpdate.getDeliveryStatus(), toUpdate.getDeliveryDate(), toUpdate.getTotalPrice(), toUpdate.getCustomerId());
						}
			}				
			});
		btnUpdateSale.setBounds(362, 57, 105, 23);
		contentPane.add(btnUpdateSale);
		
		JButton btnFindSale = new JButton("Find sale");
		btnFindSale.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(idField.getText().equals(""))
				{
					JOptionPane.showMessageDialog(null, "Please specify the id of the sale you want to change.");
				}
				else
					if(!isNumeric(idField.getText()))
					{
						JOptionPane.showMessageDialog(null, "The ID field must contain only digits.");
					}
					else
						if(salesCtrl.getSalesOrderId(idField.getText()) == null)
						{
							JOptionPane.showMessageDialog(null, "The ID must exist in the database.");
						}
						else
						{
							dateField.setText(salesCtrl.getSalesOrderId(idField.getText()).getDate());
							statusField.setText(salesCtrl.getSalesOrderId(idField.getText()).getDeliveryStatus());
							deliveryDateField.setText(salesCtrl.getSalesOrderId(idField.getText()).getDeliveryDate());
							customerField.setText(String.valueOf(salesCtrl.getSalesOrderId(idField.getText()).getCustomerId()));
							totalPriceField.setText(String.valueOf(salesCtrl.getSalesOrderId(idField.getText()).getTotalPrice()));
						}
			}
			});
		btnFindSale.setBounds(362, 107, 105, 23);
		contentPane.add(btnFindSale);
		
		JButton btnAddItemTo = new JButton("Add item to sale");
		btnAddItemTo.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				/*if(idField.getText().equals("") || pIdField.getText().equals("") || amountField.getText().equals("") || priceField.getText().equals(""))
				{
					JOptionPane.showMessageDialog(null, "Please specify the id of the sale you want to add an item to, as well as fill the fields regarding the item.");
				}
				else
					if(!isNumeric(idField.getText()) || !isNumeric(amountField.getText()) || !isReal(priceField.getText()))
					{
						JOptionPane.showMessageDialog(null, "The following fields have to contain numbers: Sale ID, Amount, Price.");
					}
					else
						if(salesCtrl.getSalesOrderId(idField.getText()) == null || productCtrl.getProductID(pIdField.getText()) == null)
						{
							JOptionPane.showMessageDialog(null, "The sale and the product must exist in the database.");
						}
						else*/
							try 
							{
								lineItemCtrl.insertLineItem(Integer.parseInt(amountField.getText()), Double.parseDouble(priceField.getText()), "sale", Integer.parseInt(pIdField.getText()), Integer.parseInt(idField.getText()));
								SalesOrder toUpdate = salesCtrl.getSalesOrderId(idField.getText());
								toUpdate.setTotalPrice(toUpdate.getTotalPrice() + Double.parseDouble(priceField.getText()) * Double.parseDouble(amountField.getText()));
								salesCtrl.updateSalesOrder(toUpdate.getId(), toUpdate.getDate(), toUpdate.getDeliveryStatus(), toUpdate.getDeliveryDate(), toUpdate.getTotalPrice(), toUpdate.getCustomerId());
								totalPriceField.setText(String.valueOf(toUpdate.getTotalPrice()));
							} 
							catch (Exception e1)
							{
								JOptionPane.showMessageDialog(null, "Error in creating line item.");
							} 
							//SalesOrder toUpdate = salesCtrl.getSalesOrderId(idField.getText());
							//toUpdate.setTotalPrice(toUpdate.getTotalPrice() + Double.parseDouble(priceField.getText()) * Double.parseDouble(amountField.getText()));
							//salesCtrl.updateSalesOrder(toUpdate.getId(), toUpdate.getDate(), toUpdate.getDeliveryStatus(), toUpdate.getDeliveryDate(), toUpdate.getTotalPrice(), toUpdate.getCustomerId());
			}
		});
		btnAddItemTo.setBounds(331, 157, 165, 23);
		contentPane.add(btnAddItemTo);
		
		JButton btnRemoveItemFrom = new JButton("Remove item from sale");
		btnRemoveItemFrom.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(idField.getText().equals("") || pIdField.getText().equals(""))
				{
					JOptionPane.showMessageDialog(null, "Please specify the id of the sale you want to remove an item from, as well as specify th.");
				}
				else
					if(!isNumeric(idField.getText()) || !isNumeric(amountField.getText()) || !isReal(priceField.getText()))
					{
						JOptionPane.showMessageDialog(null, "The following fields have to contain numbers: Sale ID, Amount, Price.");
					}
					else
						if(salesCtrl.getSalesOrderId(idField.getText()) == null || productCtrl.getProductID(pIdField.getText()) == null)
						{
							JOptionPane.showMessageDialog(null, "The sale and the product must exist in the database.");
						}
						else
						{
							ArrayList<LineItem> lineItems = lineItemCtrl.getAllLineItems();
							for(LineItem lineItem : lineItems)
								if(Integer.parseInt(idField.getText()) == lineItem.getSaleId() && Integer.parseInt(pIdField.getText()) == lineItem.getPid())
								{
									SalesOrder toUpdate = salesCtrl.getSalesOrderId(idField.getText());
									toUpdate.setTotalPrice(toUpdate.getTotalPrice() - Double.parseDouble(priceField.getText()) * Double.parseDouble(amountField.getText()));
									salesCtrl.updateSalesOrder(toUpdate.getId(), toUpdate.getDate(), toUpdate.getDeliveryStatus(), toUpdate.getDeliveryDate(), toUpdate.getTotalPrice(), toUpdate.getCustomerId());
									lineItemCtrl.deleteLineItem(String.valueOf(lineItem.getSaleId()));
									totalPriceField.setText(String.valueOf(toUpdate.getTotalPrice()));
								}
						}
			}
		});
		btnRemoveItemFrom.setBounds(331, 186, 165, 23);
		contentPane.add(btnRemoveItemFrom);
		
		JButton btnUpdateItem = new JButton("Update item in sale");
		btnUpdateItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try
				{
					LineItem lineItem = lineItemCtrl.getLineItemId(idField.getText());
					SalesOrder toUpdate = salesCtrl.getSalesOrderId(idField.getText());
					toUpdate.setTotalPrice(toUpdate.getTotalPrice() + Double.parseDouble(priceField.getText()) * Double.parseDouble(amountField.getText()));
					toUpdate.setTotalPrice(toUpdate.getTotalPrice() - lineItem.getItemPrice() * lineItem.getAmount());
					salesCtrl.updateSalesOrder(toUpdate.getId(), toUpdate.getDate(), toUpdate.getDeliveryStatus(), toUpdate.getDeliveryDate(), toUpdate.getTotalPrice(), toUpdate.getCustomerId());
					lineItem.setAmount(Integer.parseInt(amountField.getText()));
					lineItem.setItemPrice(Double.parseDouble(priceField.getText()));
					lineItemCtrl.updateLineItem(lineItem.getAmount(), lineItem.getItemPrice(), "sale", lineItem.getPid(), lineItem.getSaleId());
					totalPriceField.setText(String.valueOf(toUpdate.getTotalPrice()));
				}
				catch(Exception r)
				{
					JOptionPane.showMessageDialog(null,"Error in creating Customer Group!");
				}
			}
			});
		btnUpdateItem.setBounds(331, 216, 165, 23);
		contentPane.add(btnUpdateItem);
		
		JButton btnQuit = new JButton("Quit");
		btnQuit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.exit(EXIT_ON_CLOSE);
			}
		});
		btnQuit.setBounds(511, 267, 89, 23);
		contentPane.add(btnQuit);
		
		customerField = new JTextField();
		customerField.setBounds(134, 134, 86, 20);
		contentPane.add(customerField);
		customerField.setColumns(10);
		
		JLabel lblCustomerId = new JLabel("Customer ID");
		lblCustomerId.setBounds(25, 136, 74, 14);
		contentPane.add(lblCustomerId);
		
		JSeparator separator = new JSeparator();
		separator.setBounds(25, 271, 195, 2);
		contentPane.add(separator);
		
		JSeparator separator_1 = new JSeparator();
		separator_1.setBounds(25, 161, 195, 20);
		contentPane.add(separator_1);
	}

	public boolean isNumeric(String _str)  
	{  
	  try  
	  {  
	    long l = Long.parseLong(_str);  
	  }  
	  catch(NumberFormatException nfe)  
	  {  
	    return false;  
	  }  
	  return true;  
	}
	
	public boolean isReal(String _str)  
	{  
	  try  
	  {  
	    double l = Double.parseDouble(_str);  
	  }  
	  catch(NumberFormatException nfe)  
	  {  
	    return false;  
	  }  
	  return true;  
	}
}
